package com.example.demo.controller;

import com.example.demo.request.WxRequest;
import com.example.demo.service.MainService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

@RestController
public class MainController {


    @Resource
    private MainService mainService;


    //配置服务器使用,配置成功之后可以去掉 用于验证服务器
    @GetMapping(value = "/")
    public String mytoken(String echostr){
        System.out.println(echostr);
        return echostr;
    }


    //公众号统一入口
    @PostMapping(value = "/", consumes = MediaType.TEXT_XML_VALUE)
    public String myToken(@RequestBody WxRequest wxRequest, HttpServletResponse response){

        System.out.println("main 传入的数据>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println(wxRequest.toString());
        String message = mainService.getMessage(wxRequest);
        response.setCharacterEncoding("utf-8");
        try(Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()))) {
            out.write(message);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "error";
        }
        return "success";
    }


}
